package com.master.chat.framework.util;

import com.master.chat.framework.util.file.FileInfo;
import com.master.chat.framework.util.file.FileUploadUtils;
import com.volcengine.tos.TOSV2;
import com.volcengine.tos.TOSV2ClientBuilder;
import com.volcengine.tos.TosClientException;
import com.volcengine.tos.TosServerException;
import com.volcengine.tos.comm.HttpMethod;
import com.volcengine.tos.model.object.PreSignedURLInput;
import com.volcengine.tos.model.object.PreSignedURLOutput;
import com.volcengine.tos.model.object.PutObjectInput;
import com.volcengine.tos.model.object.PutObjectOutput;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;

public class HuoShanTOSUtil {
    private static final String TOS_ENDPOINT = "https://tos-cn-beijing.volces.com";
    private static final String REGION = "cn-beijing";
    private static final String VOLC_ACCESSKEY = "AKLTNTQ4ZjUyNWE3ZGE4NGRlOWJhZDdmOGNmYjI3NGZiYWQ";
    private static final String VOLC_SECRETKEY = "TVRreFltRmxPV1EzWXpBeU5EZzJPRGczTURZMk9UZ3lNRGd3T0dNM016QQ==";
    private static final String bucketName = "chat-master";
    private static final long TOS_EXPIRE_TIME = 36000;

    public static FileInfo upload(MultipartFile file) throws IOException {
        String filename = FileUploadUtils.extractFilename(file);
        TOSV2 tos = new TOSV2ClientBuilder().build(REGION, TOS_ENDPOINT, VOLC_ACCESSKEY, VOLC_SECRETKEY);
        // step 1. 上传本地图片到tos
        try (FileInputStream inputStream = (FileInputStream) file.getInputStream()) {
            PutObjectInput putObjectInput = new PutObjectInput().setBucket(bucketName)
                    .setKey(filename).setContent(inputStream).setContentLength(file.getSize());
            PutObjectOutput output = tos.putObject(putObjectInput);
            System.out.println("putObject succeed, object's etag is " + output.getEtag());
            System.out.println("putObject succeed, object's crc64 is " + output.getHashCrc64ecma());
        } catch (IOException e) {
            System.out.println("putObject read file failed");
            e.printStackTrace();
            throw e;
        } catch (TosClientException e) {
            // 操作失败，捕获客户端异常，一般情况是请求参数错误，此时请求并未发送
            System.out.println("putObject failed");
            System.out.println("Message: " + e.getMessage());
            if (e.getCause() != null) {
                e.getCause().printStackTrace();
            }
            throw e;
        } catch (TosServerException e) {
            // 操作失败，捕获服务端异常，可以获取到从服务端返回的详细错误信息
            System.out.println("putObject failed");
            System.out.println("StatusCode: " + e.getStatusCode());
            System.out.println("Code: " + e.getCode());
            System.out.println("Message: " + e.getMessage());
            System.out.println("RequestID: " + e.getRequestID());
            throw e;
        } catch (Throwable t) {
            // 作为兜底捕获其他异常，一般不会执行到这里
            System.out.println("putObject failed");
            System.out.println("unexpected exception, message: " + t.getMessage());
            throw t;
        }
        FileInfo fileInfo = new FileInfo();
//        String preSignedURL = getPreSignedURL(bucketName, filename);
        fileInfo.setFileName(file.getName());
        fileInfo.setFileUrl("https://chat-master.tos-cn-beijing.volces.com/" + filename);
        return fileInfo;
    }
//    public static void compressImage(String inputImagePath, String outputImagePath, long targetSizeInBytes) throws IOException {
//        File inputFile = new File(inputImagePath);
//        BufferedImage img = ImageIO.read(inputFile);
//        float quality = targetSizeInBytes * 1.0f / inputFile.length();
//        try (ImageOutputStream ios = ImageIO.createImageOutputStream(new File(outputImagePath))) {
//            ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
//            ImageWriteParam param = writer.getDefaultWriteParam();
//            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
//            param.setCompressionQuality(quality);
//            writer.setOutput(ios);
//            writer.write(null, new javax.imageio.IIOImage(img, null, null), param);
//            writer.dispose();
//        }
//    }

    public static String getPreSignedURL(String bucketName, String objectKey) {

        TOSV2 tos = new TOSV2ClientBuilder().build(REGION, TOS_ENDPOINT, VOLC_ACCESSKEY, VOLC_SECRETKEY);

        // 生成预签名链接
        try {
            PreSignedURLInput input = new PreSignedURLInput().setBucket(bucketName).setKey(objectKey)
                    .setHttpMethod(HttpMethod.GET).setExpires(TOS_EXPIRE_TIME);
            PreSignedURLOutput output = tos.preSignedURL(input);
            System.out.println("preSignedURL succeed, the signed url is " + output.getSignedUrl());
            System.out.println("preSignedURL succeed, the signed header is " + output.getSignedHeader());
            return output.getSignedUrl();
        } catch (TosClientException e) {
            // 操作失败，捕获客户端异常，一般情况是请求参数错误，此时请求并未发送
            System.out.println("preSignedURL failed");
            System.out.println("Message: " + e.getMessage());
            if (e.getCause() != null) {
                e.getCause().printStackTrace();
            }
            throw e;
        } catch (Throwable t) {
            // 作为兜底捕获其他异常，一般不会执行到这里
            System.out.println("preSignedURL failed");
            System.out.println("unexpected exception, message: " + t.getMessage());
            throw t;
        }
    }
}
